package com.workspace.chb_website.config;

import com.workspace.chb_website.bean.User;
import com.workspace.chb_website.service.WorkLogService;
import com.workspace.chb_website.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登陆成功处理方法
 */

@Component
public class SuccessHandler implements AuthenticationSuccessHandler {

    private final WorkLogService workLogService;

    @Autowired
    public SuccessHandler(WorkLogService workLogService) {
        this.workLogService = workLogService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        User currentUser = Util.getCurrentUser();
        int count = workLogService.isHasLog(currentUser.getId());
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write("{\"data\":{\"count\":"+count+",\"name\":\""+currentUser.getRealname()+"\"},\"meta\":{\"status\":200,\"message\":\"登录成功!\"}}");
        //out.write(String.valueOf(new RespBean(data, new MetaBean(200, "登录成功"))));
        out.flush();
        out.close();
    }
}
